import { Request, Response } from 'express'
import prisma from '../services/prisma'

export class WorkflowTemplateController {
    // 获取工作流模板列表
    async getTemplates(req: Request, res: Response) {
        try {
            const { type } = req.query
            const userId = req.query.userId as string

            const templates = await prisma.workflow.findMany({
                where: {
                    ...(type && { type: type as string }),
                    OR: [
                        { isPublic: true },
                        { userId }
                    ]
                },
                orderBy: {
                    createdAt: 'desc'
                },
                include: {
                    user: {
                        select: {
                            username: true,
                            avatar: true
                        }
                    }
                }
            })

            res.json(templates)
        } catch (error) {
            console.error('Error fetching templates:', error)
            res.status(500).json({ error: 'Failed to fetch templates' })
        }
    }

    // 创建工作流模板
    async createTemplate(req: Request, res: Response) {
        try {
            console.log('Creating template with data:', req.body)
            const {
                name,
                description,
                type,
                workflow,
                template,
                isPublic
            } = req.body

            // 获取或创建默认用户
            let user = await prisma.user.findFirst()
            if (!user) {
                console.log('Creating default user')
                user = await prisma.user.create({
                    data: {
                        email: 'default@example.com',
                        username: 'Default User',
                        avatar: 'https://via.placeholder.com/150'
                    }
                })
            }

            console.log('Using user:', user)

            const newTemplate = await prisma.workflow.create({
                data: {
                    name,
                    description,
                    type,
                    workflow: JSON.parse(JSON.stringify(workflow)),
                    template: JSON.parse(JSON.stringify(template)),
                    isPublic: isPublic ?? true,
                    userId: user.id
                },
                include: {
                    user: {
                        select: {
                            username: true,
                            avatar: true
                        }
                    }
                }
            })

            console.log('Created template:', newTemplate)
            res.json(newTemplate)
        } catch (error) {
            console.error('Error creating template:', error)
            res.status(500).json({ error: 'Failed to create template' })
        }
    }

    // 更新工作流模板
    async updateTemplate(req: Request, res: Response) {
        try {
            const { id } = req.params
            const {
                name,
                description,
                type,
                workflow,
                template,
                isPublic
            } = req.body

            const updatedTemplate = await prisma.workflow.update({
                where: { id },
                data: {
                    name,
                    description,
                    type,
                    workflow,
                    template,
                    isPublic
                },
                include: {
                    user: {
                        select: {
                            username: true,
                            avatar: true
                        }
                    }
                }
            })

            res.json(updatedTemplate)
        } catch (error) {
            console.error('Error updating template:', error)
            res.status(500).json({ error: 'Failed to update template' })
        }
    }

    // 删除工作流模板
    async deleteTemplate(req: Request, res: Response) {
        try {
            const { id } = req.params
            await prisma.workflow.delete({
                where: { id }
            })
            res.json({ success: true })
        } catch (error) {
            console.error('Error deleting template:', error)
            res.status(500).json({ error: 'Failed to delete template' })
        }
    }

    // 复制工作流模板
    async cloneTemplate(req: Request, res: Response) {
        try {
            const { id } = req.params
            const userId = req.body.userId

            // 1. 查找原模板
            const sourceTemplate = await prisma.workflow.findUnique({
                where: { id }
            })

            if (!sourceTemplate) {
                return res.status(404).json({ error: 'Template not found' })
            }

            // 2. 创建副本 - 确保 JSON 数据类型正确
            const newTemplate = await prisma.workflow.create({
                data: {
                    name: `${sourceTemplate.name} (复制)`,
                    description: sourceTemplate.description,
                    type: sourceTemplate.type,
                    // 使用 JSON.parse(JSON.stringify()) 来确保类型正确
                    workflow: JSON.parse(JSON.stringify(sourceTemplate.workflow)) as any,
                    template: JSON.parse(JSON.stringify(sourceTemplate.template)) as any,
                    userId: userId,
                    isPublic: false
                },
                include: {
                    user: {
                        select: {
                            username: true,
                            avatar: true
                        }
                    }
                }
            })

            res.json(newTemplate)
        } catch (error) {
            console.error('Error cloning template:', error)
            res.status(500).json({ error: 'Failed to clone template' })
        }
    }
} 